package top.chukongxiang.project.base.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import top.chukongxiang.project.base.model.response.R;

/**
 * 全局异常处理
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    //运行时异常
    @ExceptionHandler(value = RuntimeException.class)
    public R<?> runtimeExceptionHandler(RuntimeException ex) {
//        ExceptionUtils.getStackTrace(ex)
        log.error("{}", ex.getStackTrace()[0]);
        log.error("", ex);
        return R.failed("服务运行出错!");
    }


    @ExceptionHandler(value = Exception.class)
    public R<?> exceptionHandler(Exception e) {
        log.error("{}", e.getStackTrace()[0]);
        log.error("", e);
        return R.failed("服务执行出错!");
    }

    @ExceptionHandler(value = DoFailedException.class)
    public R<?> doFailedExceptionHandler(DoFailedException e) {
        return R.failed(e.getCode(), e.getMessage());
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R<?> MethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        // 从异常对象中拿到ObjectError对象
        ObjectError objectError = e.getBindingResult().getAllErrors().get(0);
        // 然后提取错误提示信息进行返回
        return R.failed(objectError.getDefaultMessage());
    }

//    MethodArgumentNotValidException
}
